package com.xywl.escort.view.order.subscribe

import android.os.Bundle
import android.os.CountDownTimer
import android.support.v4.content.ContextCompat
import android.text.Spannable
import android.text.SpannableString
import android.text.TextUtils
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.trello.rxlifecycle2.LifecycleTransformer
import com.xywl.escort.R
import com.xywl.escort.base.BaseActivity
import com.xywl.escort.bean.BaseResp
import com.xywl.escort.bean.GetOrderInfoResp
import com.xywl.escort.bean.SubscribeOrderDetailResp
import com.xywl.escort.utils.NumberFormatUtils
import com.xywl.escort.utils.ToastUtil
import com.xywl.escort.widget.GlideApp
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_subscribe_detail.*
import timber.log.Timber
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Inject


/**
 * 认购详情
 */
@Route(path = "/xy/order/subscribe/detail")
class SubscribeDetailActivity : BaseActivity(), SubscribeDetailContract.View {
    private var countdown: Countdown? = null

    @Inject
    lateinit var mPresenter: SubscribeDetailContract.Presenter

    @Autowired
    @JvmField
    var id = ""

    private var couponId = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_subscribe_detail)
        ARouter.getInstance().inject(this)
        initView()
        initData()
        addListener()
    }

    private fun initView() {
        showBackButton()
        setTitleText(R.string.order_detail)
    }

    private fun initData() {
        mPresenter.takeView(this)
        mPresenter.loadDetail(id)
    }

    private fun addListener() {
        btn_delete_order.setOnClickListener {
            mPresenter.delete(id)
        }
        btn_cancel_order.setOnClickListener {
            mPresenter.cancel(id)
        }
        btn_order_payment.setOnClickListener {
            mPresenter.getOrderInfo(id)
        }
        text_coupon.setOnClickListener {
            ARouter.getInstance().build("/xy/coupon/detail")
                    .withString("couponId", couponId)
                    .withInt("type", 1)
                    .navigation()
        }
    }

    internal inner class Countdown(millisInFuture: Long, countDownInterval: Long) : CountDownTimer(millisInFuture, countDownInterval) {
        override fun onFinish() {
            countdown!!.cancel()
            text_status.text = "付款超时"
            text_countdown.visibility = View.GONE
            btn_delete_order.visibility = View.VISIBLE
            btn_cancel_order.visibility = View.GONE
            btn_order_payment.visibility = View.GONE
        }

        override fun onTick(millisUntilFinished: Long) {
            text_countdown.text = toClock(millisUntilFinished)
        }
    }

    fun toClock(millisUntilFinished: Long): String {
        var hour = millisUntilFinished / (60 * 60 * 1000)
        var minute = (millisUntilFinished - hour * 60 * 60 * 1000) / (60 * 1000)
        var second = (millisUntilFinished - hour * 60 * 60 * 1000 - minute * 60 * 1000) / 1000
        if (second >= 60) {
            second = second % 60
            minute += second / 60
        }
        if (minute >= 60) {
            minute = minute % 60
            hour += minute / 60
        }
        var sh = ""
        var sm = ""
        var ss = ""
        if (hour < 10) {
            sh = "0" + hour.toString()
        } else {
            sh = hour.toString()
        }
        if (minute < 10) {
            sm = "0" + minute.toString()
        } else {
            sm = minute.toString()
        }
        if (second < 10) {
            ss = "0" + second.toString()
        } else {
            ss = second.toString()
        }
        return "倒计时: $sh:$sm:$ss"
    }

    override fun isActive(): Boolean {
        return false
    }

    override fun <T : Any?> bindToLife(): LifecycleTransformer<T> {
        return this.bindToLifecycle()
    }

    override fun loadDetailSuccess(dataBean: SubscribeOrderDetailResp.DataBean?) {
        text_title.text = dataBean!!.projectName
        if (null != dataBean.marketPriceYuan) {
            val marketPrice = "市场价/份 " + NumberFormatUtils.getInstance().format(dataBean.marketPriceYuan.toDouble()) + "元"
            text_market_price.text = setText(marketPrice, marketPrice.indexOf("份") + 1, marketPrice.length)
        }
        if (null != dataBean.priceYuan) {
            val subscriptionPrice = "认购价/份 " + NumberFormatUtils.getInstance().format(dataBean.priceYuan.toDouble()) + "元"
            text_subscription_price.text = setText(subscriptionPrice, subscriptionPrice.indexOf("份") + 1, subscriptionPrice.length)
        }

        GlideApp.with(this)
                .load(dataBean.coverUrl)
                .centerCrop()
                .placeholder(R.mipmap.icon_default_picture)
                .into(img_project)

        val subscriptions = dataBean.num.toString() + "份"
        text_subscriptions.text = subscriptions

        if (null != dataBean.totalPriceYuan) {
            val totalPrice = "￥ " + NumberFormatUtils.getInstance().format(dataBean.totalPriceYuan.toDouble())
            text_payable.text = totalPrice
        }

        if (!TextUtils.isEmpty(dataBean.redPacketReceiveId)) {
            couponId = dataBean.redPacketReceiveId
            layout_coupon.visibility = View.VISIBLE
            if (null != dataBean.redPacketPriceYuan) {
                val totalPrice = "￥ " + NumberFormatUtils.getInstance().format(dataBean.redPacketPriceYuan.toDouble())
                text_coupon.text = totalPrice
            }
        } else {
            layout_coupon.visibility = View.GONE
        }

        if (null != dataBean.realPayTotalYuan) {
            val totalPrice = "￥ " + NumberFormatUtils.getInstance().format(dataBean.realPayTotalYuan.toDouble())
            text_payment.text = totalPrice
        }

        // 订单状态:1-待支付，2-支付成功，3-支付失败，4-订单取消，5-订单失效 6-支付中
        when (dataBean.orderStatus) {
            1 -> {
                text_status.text = "待支付"
                val payTimeOut = dataBean.payTimeOut
                val now = dataBean.now
                val distance = getDistanceTime(now, payTimeOut)
                text_countdown.visibility = View.VISIBLE
                countdown = Countdown(distance * 1000, 1000)
                countdown!!.start()

                btn_delete_order.visibility = View.GONE
                btn_cancel_order.visibility = View.VISIBLE
                btn_order_payment.visibility = View.VISIBLE
            }
            2 -> {
                text_status.text = "已付款"
                text_countdown.visibility = View.GONE
                btn_delete_order.visibility = View.VISIBLE
                btn_cancel_order.visibility = View.GONE
                btn_order_payment.visibility = View.GONE
            }
            3 -> {
                text_status.text = "付款超时"
                text_countdown.visibility = View.GONE
                btn_delete_order.visibility = View.VISIBLE
                btn_cancel_order.visibility = View.GONE
                btn_order_payment.visibility = View.GONE
            }
            4 -> {
                text_status.text = "取消订单"
                text_countdown.visibility = View.GONE
                btn_delete_order.visibility = View.VISIBLE
                btn_cancel_order.visibility = View.GONE
                btn_order_payment.visibility = View.GONE
            }
            5 -> {
                text_status.text = "订单失效"
                text_countdown.visibility = View.GONE
                btn_delete_order.visibility = View.VISIBLE
                btn_cancel_order.visibility = View.GONE
                btn_order_payment.visibility = View.GONE
            }
            6 -> {
                text_status.text = "支付中"
                text_countdown.visibility = View.GONE
                btn_delete_order.visibility = View.GONE
                btn_cancel_order.visibility = View.GONE
                btn_order_payment.visibility = View.GONE
            }
            else -> {
            }
        }
        circleProgress.setMax(100)
        circleProgress.setProgress(100)
        // 项目状态： 1-认购中 2-已售罄 3-派单中 4-待认购 5-成长中 6-分红结束 7-项目失败 -1-未知
        when (dataBean.projectStatus) {
            1 -> {
                text_first_line.text = "认购中"
                text_second_line.visibility = View.GONE
            }
            2 -> {
                text_first_line.text = "已售罄"
                text_second_line.visibility = View.GONE
            }
            3 -> {
                text_first_line.text = "派单中"
                text_second_line.visibility = View.GONE
            }
            4 -> {
                text_first_line.text = "待认购"
                text_second_line.visibility = View.GONE
            }
            5 -> {
                text_first_line.text = "成长中"
                text_second_line.visibility = View.GONE
            }
            6 -> {
                text_first_line.text = "分红"
                text_second_line.visibility = View.VISIBLE
                text_second_line.text = "结束"
            }
            7 -> {
                text_first_line.text = "项目"
                text_second_line.visibility = View.VISIBLE
                text_second_line.text = "失败"
            }
            else -> {
            }
        }
    }

    private fun setText(text: String, start: Int, end: Int): SpannableString {
        val spanString = SpannableString(text)
        //再构造一个改变字体颜色的Span
        val span = ForegroundColorSpan(ContextCompat.getColor(this, R.color.aid_prompt_color))
        //将这个Span应用于指定范围的字体
        spanString.setSpan(span, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        val span1 = AbsoluteSizeSpan(15, true)
        spanString.setSpan(span1, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        return spanString
    }

    private fun getDistanceTime(str1: String, str2: String): Long {
        val df = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
        val one: Date
        val two: Date
        var sec: Long = 0
        try {
            one = df.parse(str1)
            two = df.parse(str2)
            val time1 = one.time
            val time2 = two.time
            val diff = time2 - time1
            sec = diff / 1000
        } catch (e: ParseException) {
            e.printStackTrace()
        }
        return sec
    }

    override fun loadDetailFailure() {
        Timber.e("loadDetailFailure")
    }

    override fun cancelSuccess(resp: BaseResp?) {
        ToastUtil.showTip(this, "取消订单成功！！！")
        finish()
    }

    override fun cancelFailure(msg: String) {
        ToastUtil.showTip(this, msg)
    }

    override fun deleteSuccess(resp: BaseResp?) {
        ToastUtil.showTip(this, "删除订单成功！！！")
        finish()
    }

    override fun deleteFailure(msg: String) {
        ToastUtil.showTip(this, msg)
    }

    override fun getOrderInfoSuccess(dataBean: GetOrderInfoResp.DataBean?) {
        ARouter.getInstance()
                .build("/xy/subscribe/order/pay/dialog")
                .withString("recordId", dataBean!!.id)
                .withString("couponId", dataBean.redPacketReceiveId)
                .withString("bandCardId", dataBean.userBankCardId)
                .withObject("couponPayMoney", dataBean.redPacketPriceYuan)
                .withObject("accountPayMoney", dataBean.fundPayMoneyYuan)
                .withObject("thirdAccountPayPrice", dataBean.thirdPartyPayMoneyYuan)
                .withInt("type", dataBean.type)
                .navigation()
    }

    override fun getOrderInfoFailure(msg: String?) {
        ToastUtil.showTip(this, msg)
    }

    override fun onDestroy() {
        super.onDestroy()

        countdown?.let {
            countdown!!.cancel()
        }
    }
}
